import 'package:extended_text/extended_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yfree/YFree.dart';
import 'package:flutter_yim/YIM.dart';
import 'package:pc/Const/IFinal.dart';
import 'package:pc/Extension/String++.dart';
import 'package:pc/Extension/special_text/my_special_text_span_builder.dart';
import 'package:pc/Model/MessageModel.dart';
import 'package:pc/View/MouseMenu.dart';
import 'package:pc/View/Views.dart';

class ConversationView {
  final page = IFinal.Others.homePage;

  Widget searchResult() {
    if (page.controller_conversation == null || page.controller_conversation!.state.conversations == null || page.controller_conversation!.state.conversations!.isEmpty) return YEmpty();
    List<ConversationModel> results = page.controller_conversation!.state.conversations!.where((conversation) => conversation.isSearch).toList();
    return CompositedTransformFollower(
      link: page.controller_conversation!.state.searchLink,
      child: YToggleWidget(
        duration: 100,
        isShowChildA: page.controller_conversation!.state.isSearching,
        childA: () => Card(
          color: Colors.transparent,
          elevation: 5,
          margin: EdgeInsets.only(top: 35),
          child: Container(
            width: 300,
            height: yScreenSize().height - 100,
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(5), border: Border.all(color: Colors.grey, width: 0.2)),
            child: results.isEmpty
                ? Center(
                    child: Text(
                      page.controller_conversation!.state.controller_search.text.isEmpty ? "请输入搜索关键字" : "暂无搜索结果",
                      style: TextStyle(color: Colors.grey),
                    ),
                  )
                : view_conversations(results, showSelection: false),
          ),
        ),
        childB: () => YEmpty(),
      ),
    );
  }

  Widget view_conversations(List<ConversationModel> conversations, {bool showSelection = true}) {
    Widget view_item(ConversationModel conversation) {
      Widget view_state() {
        if (!conversation.isMine) return YEmpty();
        final size = 15.0;
        switch (conversation.messageState) {
          case YIMEnum_MessageState.Sending:
            return Container(
              width: size,
              height: size,
              child: CircularProgressIndicator(strokeWidth: 2),
            );
          case YIMEnum_MessageState.Success_Read:
            return Container(
              width: size,
              height: size,
              child: Icon(Icons.check_circle, color: YConfig.themeColor, size: size),
            );
          case YIMEnum_MessageState.Success_UnRead:
            return Container(
              width: size,
              height: size,
              child: Icon(Icons.check_circle_outline, color: YConfig.themeColor, size: size),
            );
          case YIMEnum_MessageState.Fail:
            return Container(
              width: size,
              height: size,
              child: Icon(Icons.cancel_schedule_send_rounded, color: Colors.red, size: size),
            );
          default:
            return YEmpty();
        }
      }

      return MouseMenu(
        items: [
          PopupMenuItem(
            child: Row(
              children: [
                Icon(Icons.delete_rounded, color: Colors.red, size: 20),
                YSpacer(width: 10),
                Text("删除", style: TextStyle(color: Colors.red, fontSize: 14)),
              ],
            ),
            onTap: () {
              YIM.conversationManager.delete(
                conversationType: YIMEnum_ConversationType.P2P,
                conversationID: conversation.conversationID,
                deleteServer: true,
                callback: (isSuccess) {
                  yToast(isSuccess ? "删除成功" : "删除失败");
                },
              );
            },
          ),
        ],
        child: GestureDetector(
          child: YButton(
            padding: EdgeInsets.all(10),
            color: showSelection && conversation.isSelect ? Color.fromARGB(255, 221, 221, 221) : Color.fromARGB(255, 246, 246, 246),
            enable: !conversation.isSelect,
            child: Row(
              children: [
                Stack(
                  clipBehavior: Clip.none,
                  children: [
                    YImageCorner(40, 40, conversation.avatar, 5),
                    Positioned(top: -5, right: -10, child: Views.view_badge(conversation.unReadCount)),
                  ],
                ),
                YSpacer(width: 10),
                Expanded(
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Expanded(child: Text(conversation.name, style: TextStyle(fontSize: 12))),
                          YSpacer(width: 10),
                          Text(conversation.date.toString(), style: TextStyle(color: Colors.grey, fontSize: 10)),
                        ],
                      ),
                      YSpacer(height: 5),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Expanded(
                            child: ExtendedText(
                              conversation.content.fixAutoLines(),
                              strutStyle: StrutStyle(forceStrutHeight: true),
                              specialTextSpanBuilder: mySpecialTextSpanBuilder,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: Colors.grey, fontSize: 10),
                            ),
                          ),
                          YSpacer(width: 10),
                          view_state(),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
            onTap: () {},
          ),
          onPanDown: (details) {
            //清空搜索框
            page.controller_conversation!.state.controller_search.clear();
            page.controller_conversation!.state.conversations!.forEach((conversation) => conversation.isSearch = false);
            //判断是否重复选中
            final selectConversation = page.controller_conversation!.getSelectConversation(conversations: conversations);
            if (selectConversation != null && selectConversation.conversationID == conversation.conversationID) return;
            //刷新状态
            conversation.unReadCount = 0;
            page.controller_chat!.state.messages.clear();
            selectConversation?.isSelect = false;
            conversation.isSelect = true;
            page.controller_conversation!.clearUnReadCount();
            page.controller_conversation!.sendMessageReceipt();
            page.setState(() {});
            page.controller_chat!.loadMessages();
          },
        ),
      );
    }

    return ListView.builder(
      primary: false,
      shrinkWrap: true,
      padding: EdgeInsets.zero,
      itemCount: conversations.length,
      itemBuilder: (context, index) => view_item(conversations[index]),
    );
  }

  Widget conversation() {
    Widget searchBar() {
      return Container(
        width: yScreenSize().width,
        padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
        color: Color.fromARGB(255, 246, 246, 246),
        child: CompositedTransformTarget(
          link: page.controller_conversation!.state.searchLink,
          child: Container(
            decoration: BoxDecoration(
              color: Color.fromARGB(255, 233, 233, 233),
              borderRadius: BorderRadius.circular(5),
              border: Border.all(color: (page.controller_conversation?.state.isSearching ?? false) ? YConfig.themeColor : Colors.transparent, width: 1),
            ),
            alignment: Alignment.center,
            child: Row(
              children: [
                Container(
                  padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
                  child: Icon(Icons.search_rounded, size: 15, color: Colors.grey),
                ),
                Expanded(
                  child: TextFormField(
                    focusNode: page.controller_conversation!.state.focusNode_search,
                    controller: page.controller_conversation!.state.controller_search,
                    minLines: 1,
                    maxLines: 1,
                    style: TextStyle(fontSize: 12),
                    cursorWidth: 1,
                    decoration: InputDecoration(
                      isCollapsed: true,
                      hintText: "搜索",
                      hintStyle: TextStyle(fontSize: 12, color: Colors.grey),
                      contentPadding: EdgeInsets.fromLTRB(0, 10, 5, 10),
                      border: InputBorder.none,
                    ),
                    onChanged: (value) {
                      page.controller_conversation!.state.conversations!.forEach((conversation) {
                        conversation.isSearch = value.isEmpty ? false : conversation.name.contains(value) || conversation.content.contains(value);
                      });
                      page.setState(() {});
                    },
                  ),
                ),
                page.controller_conversation!.state.controller_search.text.isEmpty
                    ? YEmpty()
                    : YButton(
                        isInk: true,
                        margin: EdgeInsets.fromLTRB(0, 0, 5, 0),
                        padding: EdgeInsets.all(2),
                        borderRadius: BorderRadius.circular(99),
                        decoration: BoxDecoration(color: Colors.grey),
                        child: Icon(Icons.clear_rounded, size: 10, color: Colors.white),
                        onTap: () {
                          page.controller_conversation!.state.controller_search.clear();
                          // page.setState(() {});
                        },
                      ),
              ],
            ),
          ),
        ),
      );
    }

    return Container(
      color: Color.fromARGB(255, 246, 246, 246),
      child: page.controller_conversation!.state.conversations!.isEmpty
          ? Center(child: Image.asset("images/bg_empty_conversation.png", width: 150))
          : Column(
              children: [
                searchBar(),
                view_conversations(page.controller_conversation!.state.conversations!),
              ],
            ),
    );
  }
}
